<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-08-18 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2023-01-10 16:17:28
 * 授权管理控制器
 */

namespace app\admin\logic;
use app\common\logic\BaseLogic as BaseLogic;

class AdminAuth extends BaseLogic {

    public function __construct() {
        parent::__construct();
        
		$this->categoryModel = model('SystemCategory', 'admin');
		$this->userModel = model('SystemUser', 'admin');
	}
	
	/**
	 * 获取侧边栏菜单
	 * @param    string                    $position [description]
	 * @return   [type]                              [description]
	 * @Author   lianlianzan(13040@qq.com)
	 * @DateTime 2020-11-07
	 */
	public function getAdminSidebarMenu($groupid) {
		$module = strtolower(MODULE_NAME);
		//echo $module;exit;

// 		if (0 && $module == 'weixin_manage') {
// 			$isIndependence = 1;
// 			$sideBarMenuCategory = include_once(APP_PATH.'weixin_manage/menu.php');
// 			//echo '菜单数组:';print_r($sideBarMenuCate);exit;
// 		} else {
// 			//echo '菜单树:';print_r($sidebarMenuGroup);exit;
// 		}
		
		//获取菜单分类
		$sideBarMenuCategory = $this->categoryModel->getMenuCate($groupid);
		//echo '菜单分类:';print_r($sideBarMenuCategory);
		
		//根据组别获取菜单的树
		list($menuTree, $selfMenuRule, $subsidiaryArr, $nowRule) = $this->getNewMenuTree($groupid);
		//echo '菜单树:';print_r($menuTree);
		//echo '父级菜单';print_r($selfMenuRule);exit;
		if ($selfMenuRule['is_selfauth'] == 1) {
			$isSelfauth = 1;
		} else {
			$isSelfauth = 0;
		}
		if ($selfMenuRule['is_selfmenu'] == 1) {
			$isSelfmenu = 1;
			$sideBarMenuCategory = include(APP_PATH.$module.'/config/menu.php');
			//print_r($sideBarMenuCategory);exit;
		} else {
			$isSelfmenu = 0;
		}
		if ($sideBarMenuCategory) {
			$sidebarMenuGroup = array();
			foreach ($sideBarMenuCategory as $key => $value) {
				$tmpMenu = array();
				//把树拼凑给每个分类
				foreach ($menuTree as $key2 => $value2) {
					if ($value2['cid'] == $value['id']) {
						$tmpMenu[] = $value2;
					}
				}
				$sidebarMenuGroup[$value['id']] = $tmpMenu;
			}
		}
		return [$isSelfauth, $isSelfmenu, $sideBarMenuCategory, $sidebarMenuGroup, $subsidiaryArr, $nowRule];
	}

	/**
	 * 取得树形结构的菜单
	 * @param    [type]                    $groupid [description]
	 * @return   [type]                             [description]
	 * @Author   lianlianzan(13040@qq.com)
	 * @DateTime 2017-11-09
	 */
	public function getNewMenuTree($groupid) {
		//获取权限列表
		$groupAccessModel = model('SystemGroupAccess', 'admin');
		list($accessList) = $groupAccessModel->search(['groupid'=>$groupid]);
		//print_r($accessList);exit;
		$currentModule = strtolower(MODULE_NAME); //模块名
		$currentController = strtolower(CONTROLLER_NAME); //控制器名
		//获取规则树
		$ruleModel = model('SystemRule', 'admin');
		$data = $ruleModel->where([['state', '=', 1]])->order('vieworder asc')->select();
		$ruleList = $data->toArray(); //转换为数组
		//print_r($ruleList);
		$nowRule = [ //默认是首页
			'id'			=> 0,
			'parentid' 		=> 0,
			'module' 		=> 'admin',
			'controller' 	=> 'index',
		];
		$selfMenuRule = $subsidiaryArr = [];
		$parents = $childs = $subs = [];
		foreach ($ruleList as $key => $value) {
			$value['current'] = 0;
			$value['checked'] = $this->is_checked($value, $groupid, $accessList) ? ' checked' : '';
			if ($value['parentid']) {
				$module = $value['module'];
				$controller = $value['controller'];
				$action = $value['action'];
				$parameter = $value['parameter'];
				$value['url'] = url("{$module}/{$controller}/{$action}?{$parameter}");
				if (strtolower($module) == $currentModule && strtolower($controller) == $currentController) {
					$value['current'] = 1;
					$nowRule = $value;
				}
				if (strtolower($module) == $currentModule) { //独立菜单
					$selfMenuRule = $value;
				}
				if ($value['level'] == 3) {
					$subs[$value['parentid']][$value['id']] = $value;
				} else {
					$childs[$value['parentid']][$value['id']] = $value;
				}
				//$subs = explode(",", $value['subs']);
				//if (count($subs) > 1) {
				//	$subsidiaryArr = array_merge($subsidiaryArr, $subs);
				//}
				if ($value['subsidiary']) {
					$subsidiaryArr[$value['id']] = array(
						'id'			=> $value['id'],
						'parentid'		=> $value['parentid'],
						'module' 		=> $value['module'],
						'controller' 	=> $value['controller'],
						'subsidiary' 	=> $value['subsidiary'],
					);
				}
			} else {
				$value['url'] = '';
				$parents[$value['id']] = $value;
			}
		}
		//echo '父级：';print_r($parents);echo '儿子级：';print_r($childs);echo '子级：';print_r($subs);echo '当前菜单：';print_r($nowRule);exit;
		//echo '当前菜单：';print_r($nowRule);exit;
		
		foreach ($childs as $key => $value) {
			foreach ($value as $key2 => $value2) {
				$nowRule['firstid'] = 0;
				if ($nowRule && $value2['id'] == $nowRule['parentid']) {
					$childs[$key][$key2]['current'] = 1;
					if ($nowRule['level'] == 3) {
						$nowRule['firstid'] = $value2['parentid'];
					}
				}
				if (isset($subs[$key2])) {
					$childs[$key][$key2]['hassub'] = 1;
					$childs[$key][$key2]['subs'] = $subs[$key2];
				} else {
					$childs[$key][$key2]['hassub'] = 0;
					$childs[$key][$key2]['subs'] = [];
				}
			}
		}
		//echo '子级：';print_r($childs);echo 'subs:';print_r($subs);
		
		foreach ($parents as $key => $value) {
			if ($nowRule && $value['id'] == $nowRule['parentid']) {
				$parents[$key]['current'] = 1;
			}
			if ($nowRule && $nowRule['firstid'] && $value['id'] == $nowRule['firstid']) {
				$parents[$key]['current'] = 1;
			}
			if (isset($childs[$key])) {
				$parents[$key]['hassub'] = 1;
				$parents[$key]['childs'] = $childs[$key];
			} else {
				$parents[$key]['hassub'] = 0;
				$parents[$key]['childs'] = [];
			}
		}
		//echo '父级：';print_r($parents);
		
		return [$parents, $selfMenuRule, $subsidiaryArr, $nowRule];
	}

	/**
	 * 检查指定菜单是否有权限
	 * @param array $data menu表中数组
	 * @param int $roleid 需要检查的角色ID
	 */
	protected function is_checked($data, $groupid, $accessArr) {
		if ($data['module'] == '') {
			return false;
		}
		$mdata = array();
		$mdata['groupid'] = $groupid;
		$mdata["m"] = $data['module'];
		$mdata["c"] = $data['controller'];
		$mdata["a"] = $data['action'];
		//print_r($mdata);
		//print_r($accessArr);exit;
		$check = in_array($mdata, $accessArr);
		if ($check) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 按父ID查找菜单子项
	 * @param integer $parentid   父菜单ID
	 * @param integer $with_self  是否包括他自己
	 */
	public function admin_menu($cateId=0, $parentid=0, $groupid=0, $with_self=false) {
		//父节点ID
		$parentid = (int) $parentid;
		$result = $this->where(array('cid'=>$cateId, 'parentid'=>$parentid, 'state'=>1))->order('vieworder desc')->select();
		$result = $result->toArray(); //转换为数组
		//print_r($this->getLastSql());echo '<br>';
		if ($with_self) {
			$result2[] = $this->where(array('id' => $parentid))->find();
			$result = array_merge($result2, $result);
		}
		//print_r($result);

		//权限检查
		//$groupid = session("s_groupid");
		//print_r($groupid);

		$privdb = model('SystemGroupAccess', 'admin'); //实例化权限表

		$array = array();
		foreach ($result as $v) {
			//方法
			$action = $v['action'];
			//public开头的通过
			if (preg_match('/^public_/', $action)) {
				$array[] = $v;
			} else {
				if (preg_match('/^ajax_([a-z]+)_/', $action, $_match)) {
					$action = $_match[1];
				}
				$map = array(
					'm' 		=> $v['module'],
					'c' 		=> $v['controller'],
					//'a' 		=> $action,
					'groupid' 	=> $groupid,
				);
				$check = $privdb->where($map)->find();
				//echo $privdb->getLastSql();echo '<br>';
				if ($check) {
					$array[] = $v;
				}
			}
		}
		//print_r($array);

		return $array;
	}
	
	/**
	 * 检测规则权限
	 */
	public function checkAuth($groupid=0, $isSelfmenu=0, $subsidiaryArr=[]) {
		$parentRule = [
			'id' 		=> 0,
			'parentid' 	=> 0
		];
		$module = MODULE_NAME; //模块名
		$controller = CONTROLLER_NAME; //控制器名
		if ($module == 'admin' && $controller == 'Index') {
			return [1, $parentRule];
		}
		$module = strtolower($module);
		$controller = strtolower($controller);
		//echo '当前模块module:'.$module;echo '<br>当前控制器controller:'.$controller;exit;
		//echo '附属菜单:';print_r($subsidiaryArr);exit;

		$groupAccessModel = model('SystemGroupAccess', 'admin'); //实例化权限表
		if ($isSelfmenu == 1) { //独立菜单的情况
			$data = [
				'groupid' 	=> $groupid,
				'm'			=> $module,
			];
			$count = $groupAccessModel->where($data)->count();
			//echo 'getLastSql:';echo $groupAccessModel->getLastSql();
			return [$count, $parentRule];
		} else {
			$data = [
				'groupid' 	=> $groupid,
				'm'			=> $module,
				'c'			=> $controller,
			];
			$count = $groupAccessModel->where($data)->count();
			//echo 'getLastSql:';echo $groupAccessModel->getLastSql();
			if ($count > 0) {
				return [$count, $parentRule];
			} else {
				//检测附属菜单控制器
				foreach ($subsidiaryArr as $key => $value) {
					if (strtolower($value['module']) != $module) {
						continue;
					}
					if (strpos(strtolower($value['subsidiary']), $controller) !== false) {
						//echo '父级菜单:';print_r($value);exit;
						$data = [
							'groupid' 	=> $groupid,
							'm'			=> $module,
							'c'			=> $value['controller'],
						];
						//print_r($data);exit;
						$count = $groupAccessModel->where($data)->count();
						return [$count, $parentRule];
						//return [$count, $value];
					}
				}
			}
		}
		return [0, $parentRule];
	}
	
}